package net.wicp.tams.common.binlog.self;

import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.JmxUtil;
import net.wicp.tams.common.apiext.StringUtil;

/***
 * 给客户端提供工具方法
 * 
 * @author zhoujunhui
 *
 */
public abstract class MBeanUtil {

	public static JMXConnector getConn(String taskId) {
		JMXConnector conn = JmxUtil.connect(StringUtil.buildPort(taskId));
		return conn;
	}

	public static ObjectName getBinlogControlMBean(JMXConnector conn) {
		ObjectName bean = JmxUtil.queryMBean(conn, "Commons:name=BinlogControl");
		return bean;
	}

	/***
	 * 停止服务
	 * 
	 * @param conn
	 * @return
	 */
	public static Result stopTask(JMXConnector conn) {
		ObjectName bean = MBeanUtil.getBinlogControlMBean(conn);
		try {
			conn.getMBeanServerConnection().invoke(bean, "stop", null, null);
			return Result.getSuc();
		} catch (Exception e) {
			return Result.getError(e.getMessage());
		}
	}

	/***
	 * 重置计数器
	 * 
	 * @param conn
	 * @return
	 */
	public static Result resetNum(JMXConnector conn) {
		ObjectName bean = MBeanUtil.getBinlogControlMBean(conn);
		try {
			conn.getMBeanServerConnection().invoke(bean, "resetNum", null, null);
			return Result.getSuc();
		} catch (Exception e) {
			return Result.getError(e.getMessage());
		}
	}
}
